package com.itany.conf;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {


    //@Qualifier==ref
    @Bean(name="shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager")
                                                          SecurityManager securityManager){
        System.out.println("--------------shiroFilter已经加载----------------");
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);
        //配置URL登录成功
        bean.setLoginUrl("/manager/showLogin");
        //授权失败界面
        bean.setUnauthorizedUrl("/manager/backend/index.html");
        //配置访问权限
        LinkedHashMap<String,String> map = new LinkedHashMap<String,String>();
        map.put("/manager/showBookList","authc,perms[user:find]");
        bean.setFilterChainDefinitionMap(map);
        return bean;

    }


    @Bean(name="securityManager")
    public SecurityManager securityManager(@Qualifier("JdbcRealm")AuthorizingRealm realm){
        System.out.println("--------------SecurityManager已经加载----------------");
        DefaultWebSecurityManager manager =new DefaultWebSecurityManager();
        manager.setRealm(realm);
        return manager;
    }


    @Bean(name="JdbcRealm")
    public JdbcRealm authRealm(@Qualifier("dataSource")
                                           DataSource dataSource){
        System.out.println("--------------JdbcRealm已经加载----------------");
        JdbcRealm jdbcRealm=new JdbcRealm();
        jdbcRealm.setDataSource(dataSource);
        jdbcRealm.setPermissionsLookupEnabled(true);
        jdbcRealm.setAuthenticationQuery("select password from t_manager_user where username=?");
        jdbcRealm.setUserRolesQuery("select r.name from t_manager_user u left join t_user_role ur on u.id=ur.id left join t_role r on ur.id=r.id where u.username=?");
        jdbcRealm.setPermissionsQuery("select p.sname from t_role r left join t_role_permission rp on r.id=rp.roleid left join t_permission p on rp.permissionid=p.id where r.name=?");
        return jdbcRealm;

    }


}
